#include "string1.h"
#include <cstring>
int String::str_num = 0;
String::String()
{
    const char * default_str = "C++";
    const int default_len = std::strlen(default_str);
    str = new char[default_len + 1];
    std::strcpy(str, default_str);
    len = default_len;
    str_num += 1;
}

String::String(const char *aStr)
{
    len = std::strlen(aStr);
    str = new char[len + 1];
    std::strcpy(str, aStr);
    str_num += 1;
}

String::String(const String & aStr)
{
    len = aStr.len;
    str = new char[len + 1];
    std::strcpy(str, aStr.str);
    str_num += 1;
}

String::~String()
{
    using std::cout;
    using std::endl;
    cout << str << " will dealloc " << str_num << " lefted ." << endl;
    delete[] str;
    str_num -= 1;
}

int String::howManay()
{
    return str_num;
}

char & String::operator[](int index) 
{
    return str[index];
}

const char & String::operator[](int index) const
{
    return str[index];
}

String & String::operator=(String &aString)
{
    // 注意，对象是不能做比较的，只能比较指针
    if (this == &aString)
    {
        return aString;
    }
    delete[] str;
    str = new char[aString.len + 1];
    std::strcpy(str, aString.str);
    len = aString.len;
    return *this;
}

String & String::operator=(const char *aStr)
{
    delete[] str;
    const int strlen = std::strlen(aStr) + 1;
    str = new char[strlen];
    std::strcpy(str, aStr);
    len = strlen;
    return *this;
}

std::ostream & operator<< (std::ostream &os, String &aStr) {
    os << aStr.str;
    return os;
}

void operator>>(std::istream &is, String &aStr) {
    char *input = new char[String::C_IPUT_LIMIT];
    is.getline(input, String::C_IPUT_LIMIT);
    aStr.str = input;
    aStr.len = std::strlen(input);
}
